package com.hbun.cxcy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hbun.cxcy.common.utils.PageUtils;
import com.hbun.cxcy.common.utils.Query;
import com.hbun.cxcy.entity.Achievement;
import com.hbun.cxcy.entity.File;
import com.hbun.cxcy.mapper.AchievementMapper;
import com.hbun.cxcy.service.AchievementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbun.cxcy.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mahaunyu
 * @since 2022-01-24
 */
@Service
public class AchievementServiceImpl extends ServiceImpl<AchievementMapper, Achievement> implements AchievementService {

    @Autowired
    FileService fileService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<Achievement> wrapper = new QueryWrapper<>();
        wrapper.eq("status",1).orderByDesc("create_time");
        IPage<Achievement> page = this.page(new Query<Achievement>().getPage(params),
                wrapper);
        return new PageUtils(page);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveWithCustom(Achievement achievements) {
        achievements.setCreateTime(new Date());
        achievements.setUpdateTime(new Date());
        this.save(achievements);
        // 添加到file表
        String url = achievements.getAchievementPrictrueUrl();
        if (!StringUtils.isEmpty(url)){
            File file = new File();
            String suffix = url.split("\\.")[1];
            String[] strings = url.split("/");
            String name = strings[strings.length-1];
            String type = "achievement";
            file.setType(type);
            file.setName(name);
            file.setStatus(1);
            file.setSuffix(suffix);
            file.setFilePath(url);
            file.setCreateTime(new Date());
            file.setUpdateTime(new Date());
            fileService.save(file);
        }

    }

    @Override
    public void updateByIdWithCustom(Achievement achievements) {
        achievements.setUpdateTime(new Date());
        this.updateById(achievements);
    }
}
